import type { arrive_bill, require_order, stock_order, t_reserv_bill, t_reserv_candidates } from '@/types/billdata'
import { make_billcode, max, sum, today } from './common'
import { useDbStore } from '@/stores/modules/database'
import type { pd_qrcode } from '@/types/producedata'
import { min } from 'date-fns'

export const set_my_reserv = (billcode: string, c: t_reserv_candidates[]) => {
  const dbStore = useDbStore()
  const all_my_reserv = dbStore.reserv_bill.filter((r) => r.requrie_bill === billcode)
  c.forEach((r) => {
    r.myreserved = sum(all_my_reserv.filter((s) => s.type === r.type && s.supply_bill === r.billcode).map((s) => s.qty))
  })
}
export const list_reserv_candidates = (require: require_order) => {
  const dbStore = useDbStore()
  const materialcode = typeof require.material === 'string' ? require.material : require.material.code
  const result: t_reserv_candidates[] = []
  const all_my_stock_reserv = dbStore.reserv_bill
    .filter((r) => r.type === '库存' && materialcode === r.materialcode)
    .map((r) => r.materialcode)
  const all_my_order_reserv = dbStore.reserv_bill
    .filter((r) => r.type === '订单' && r.requrie_bill === require.billcode)
    .map((r) => r.supply_bill)
  const all_my_arrive_reserv = dbStore.reserv_bill
    .filter((r) => r.type === '到货' && r.requrie_bill === require.billcode)
    .map((r) => r.supply_bill)
  const all_avaliable_stock = dbStore.materialStock.filter((r) => r.avaliable > 0 && materialcode === r.code).map((r) => r.code)
  const all_avaliable_order = dbStore.stockorder
    .filter(
      (r) =>
        r.order_qty - r.arrived_qty - r.reserved_qty > 0 &&
        (typeof r.material === 'string' ? r.material : r.material.code) === materialcode
    )
    .map((r) => r.billcode)
  const all_avaliable_arrive = dbStore.arrive
    .filter(
      (r) =>
        r.arrive_qty - r.stockin_qty - r.reserved_qty > 0 &&
        (typeof r.material === 'string' ? r.material : r.material.code) === materialcode
    )
    .map((r) => r.billcode)

  const materialStock = dbStore.materialStock.find(
    (r) => all_avaliable_stock.indexOf(r.code) >= 0 || all_my_stock_reserv.indexOf(r.code) >= 0
  )
  if (materialStock) {
    result.push({
      billcode: materialStock.code,
      type: '库存',
      supplyqty: materialStock.qty - materialStock.locked,
      reserved: materialStock.reserv,
      reservable: Math.max(materialStock.avaliable, 0),
      myreserved: 0,
      materialcode: materialcode
    })
  }
  const r2 = dbStore.stockorder.filter(
    (r) => all_avaliable_order.indexOf(r.billcode) >= 0 || all_my_order_reserv.indexOf(r.billcode) >= 0
  )
  r2.forEach((r) => {
    result.push({
      billcode: r.billcode,
      type: '订单',
      supplyqty: r.order_qty - r.arrived_qty,
      reserved: r.reserved_qty,
      reservable: Math.max(r.order_qty - r.arrived_qty - r.reserved_qty, 0),
      myreserved: 0,
      materialcode: materialcode
    })
  })
  const r3 = dbStore.arrive.filter(
    (r) => all_avaliable_arrive.indexOf(r.billcode) >= 0 || all_my_arrive_reserv.indexOf(r.billcode) >= 0
  )
  r3.forEach((r) => {
    result.push({
      billcode: r.billcode,
      type: '到货',
      supplyqty: r.arrive_qty - r.stockin_qty,
      reserved: r.reserved_qty,
      reservable: Math.max(r.arrive_qty - r.stockin_qty - r.reserved_qty, 0),
      myreserved: 0,
      materialcode: materialcode
    })
  })
  set_my_reserv(require.billcode, result)
  return result
}

export const get_reserv_seq = () => {
  const dbStore = useDbStore()
  if (dbStore.reserv_bill.length === 0) return 1
  return max(dbStore.reserv_bill.map((r) => r.seq)) + 1
}
export const make_reserv = (c: t_reserv_candidates, o: require_order) => {
  const dbStore = useDbStore()
  const materialcode = typeof o.material === 'string' ? o.material : o.material.code
  const result: t_reserv_bill = {
    billcode: make_billcode('RV'),
    requrie_bill: o.billcode,
    supply_bill: c.billcode,
    qty: Math.min(c.reservable, o.order_qty - o.stockout_qty - o.reserved_qty),
    docdate: today(),
    seq: get_reserv_seq(),
    type: c.type,
    materialcode: materialcode
  }
  dbStore.addReservBill(result)
  o.reserved_qty += result.qty
  if (c.type === '库存') {
    dbStore.reservMaterialStock(c.materialcode, result.qty)
  } else if (c.type === '到货') {
    const arr = dbStore.reservArriveBill(c.billcode, result.qty)
  } else if (c.type === '订单') {
    dbStore.reservStockOrder(c.billcode, result.qty)
  }
  dbStore.saveRequireOrder()
  return result
}
export const release_reserv = (c: t_reserv_candidates, o: require_order) => {
  const dbStore = useDbStore()
  const r_bills = dbStore.reserv_bill.filter((r) => r.requrie_bill === o.billcode)
  r_bills.forEach((r) => {
    if (r.type === '到货') {
      dbStore.reservArriveBill(c.billcode, 0 - r.qty)
    }
    if (r.type === '库存') {
      dbStore.reservMaterialStock(c.materialcode, 0 - r.qty)
    }
    if (r.type === '订单') {
      dbStore.reservStockOrder(c.billcode, 0 - r.qty)
    }
    o.reserved_qty -= r.qty
    r.qty = 0
  })
  dbStore.reserv_bill = dbStore.reserv_bill.filter((s) => s.qty !== 0)
  dbStore.saveRequireOrder()
  dbStore.saveReservBill()
}
/*
export const reserv_cover_qrcode = (r_bill?: t_reserv_bill) => {
  if (!r_bill) return
  if (r_bill.cover_qrcode_qty >= r_bill.qty || r_bill.type !== '到货') return
  const dbStore = useDbStore()
  const cover_qty = r_bill.qty - r_bill.cover_qrcode_qty
  const qrcodes = dbStore.qrcode.filter((r) => r.arrive_bill === r_bill.supply_bill).filter((r) => r.qty - r.reserv_qty > 0)
  let tmp_qty = cover_qty
  for (let i = 0; i <= qrcodes.length; i++) {
    const _c_qty = Math.min(qrcodes[i].qty - qrcodes[i].reserv_qty, tmp_qty)
    dbStore.addReservQrCode({
      materialcode: r_bill.materialcode,
      qrcode: qrcodes[i].qrcode,
      reserv_bill: r_bill.billcode,
      qty: _c_qty,
      require_bill: r_bill.requrie_bill
    })
    tmp_qty -= _c_qty
    qrcodes[i].reserv_qty += _c_qty
    r_bill.cover_qrcode_qty += _c_qty
    if (tmp_qty === 0) break
  }
  dbStore.saveReservBill()
  dbStore.saveQrCode()
}*/
export const reserv_from_order_to_arrive = (stockorder: stock_order, arrive: arrive_bill) => {
  const dbStore = useDbStore()
  const tran_qty = Math.min(stockorder.reserved_qty, arrive.arrive_qty)
  const reserv_bills = dbStore.reserv_bill
    .filter((r) => r.type === '订单' && r.supply_bill === stockorder.billcode)
    .sort((a, b) => {
      return a.seq - b.seq
    })
  let swap_qty = tran_qty
  for (let i = 0; i < reserv_bills.length; i++) {
    const q = Math.min(reserv_bills[i].qty, swap_qty)
    const t = JSON.parse(JSON.stringify(reserv_bills[i])) as t_reserv_bill
    t.qty = arrive.arrive_qty
    t.supply_bill = arrive.billcode
    //t.billcode = make_billcode('RV')
    t.docdate = today()
    t.seq = get_reserv_seq()
    t.type = '到货'
    dbStore.addReservBill(t)
    reserv_bills[i].qty -= arrive.arrive_qty
    swap_qty -= q
    if (swap_qty === 0) break
  }
  dbStore.reserv_bill = dbStore.reserv_bill.filter((s) => s.qty !== 0)
  stockorder.reserved_qty -= tran_qty
  dbStore.saveStockInBill()
  dbStore.saveReservBill()
}

export const reserv_from_arrive_to_stock = (arrive: arrive_bill, qty: number) => {
  const dbStore = useDbStore()
  const materialcode = typeof arrive.material === 'string' ? arrive.material : arrive.material.code
  const tran_qty = Math.min(arrive.reserved_qty, arrive.stockin_qty)
  const reserv_bills = dbStore.reserv_bill
    .filter((r) => r.type === '到货' && r.supply_bill === arrive.billcode)
    .sort((a, b) => {
      return a.seq - b.seq
    })
  let swap_qty = tran_qty
  for (let i = 0; i < reserv_bills.length; i++) {
    const q = Math.min(reserv_bills[i].qty, swap_qty)
    const t = JSON.parse(JSON.stringify(reserv_bills[i])) as t_reserv_bill
    t.qty = qty
    t.supply_bill = materialcode
    t.billcode = make_billcode('RV')
    t.docdate = today()
    t.seq = get_reserv_seq()
    t.type = '库存'
    dbStore.addReservBill(t)
    reserv_bills[i].qty -= qty
    swap_qty -= q
    if (swap_qty === 0) break
  }
  dbStore.reserv_bill = dbStore.reserv_bill.filter((s) => s.qty !== 0)
  arrive.reserved_qty -= tran_qty
  dbStore.saveArriveCode()
  dbStore.saveReservBill()
  dbStore.reservMaterialStock(materialcode, tran_qty)
}
export type t_reserv_info = {
  h: number
  t: { type: string; qty: number }[]
}
export const get_reserv_from_order = (order: string) => {
  const dbStore = useDbStore()
  const require = dbStore.require_order.find((r) => r.billcode === order)
  if (!require) return undefined
  if (require.reserved_qty === 0) return undefined
  const reserv_bill = dbStore.reserv_bill.filter((r) => r.requrie_bill === order)
  const table: { type: string; qty: number }[] = []
  reserv_bill.forEach((r) => {
    const row = table.find((s) => s.type === r.type)
    if (row) row.qty += r.qty
    else table.push({ type: r.type, qty: r.qty })
  })
  const result: t_reserv_info = { h: require.reserved_qty, t: table }
  return result
}
export const erase_reserv_for_stock = (require_id: string, qty: number) => {
  const dbStore = useDbStore()
  const require = dbStore.require_order.find((r) => r.billcode === require_id)!
  const reserv = dbStore.reserv_bill.find((r) => r.requrie_bill === require_id && r.type === '库存')
  require.reserved_qty -= qty
  dbStore.saveRequireOrder()
  if (reserv) {
    reserv.qty -= qty
    dbStore.saveReservBill()
  }
}
